package com.vd.tbsms.ui;

import java.awt.EventQueue;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.vd.tbsms.Status;
import com.vd.tbsms.parse.PropParse;
import com.vd.tbsms.process.LoadResProcess;
import com.vd.tbsms.process.ProcessCallBack;
import com.vd.tbsms.process.SendProcess;
import com.vd.tbsms.resource.XlsResource;
import com.vd.tbsms.resource.Resource.Type;

/**
 * @desc 发送工具UI
 * @author tudongyun
 * 
 */
public class TbsmsUI extends JFrame {
	private static Log log = LogFactory.getLog(TbsmsUI.class);
	private static final long serialVersionUID = 1L;
	private JPanel jPanelConfig;
	private JScrollPane jScrollPaneDetail;
	private JTable jTable;
	private JTextField jTextUser;
	private JPasswordField jPasswordField;
	private JTextPane jTextPane;
	private LoadResProcess loadResProcess;
	private JCheckBox jCheckBoxIsTable;
	private JTextField jTextSubject;
	private SendProcess sendProcess;
	private TbsmsTableModel tbsmsTableModel;

	private JButton jButtonLoad;
	private JButton jButtonSend;

	public TbsmsUI() {
		initComponents();
		initConfig();
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setExtendedState(MAXIMIZED_BOTH);
		setTitle("邮件发送工具  1.0");
	}

	public TbsmsUI(LoadResProcess loadResProcess, SendProcess sendProcess) {
		this();
		this.loadResProcess = loadResProcess;
		this.sendProcess = sendProcess;
	}

	private void initComponents() {
		jPanelConfig = new JPanel();
		jPanelConfig.setBorder(new TitledBorder("系统设置"));
		GridBagLayout frameLayout = new GridBagLayout();
		this.getContentPane().setLayout(frameLayout);
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.BOTH;
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.weightx = 1;
		gbc.weighty = 0.12;
		this.getContentPane().add(jPanelConfig, gbc);
		jScrollPaneDetail = new JScrollPane();
		jScrollPaneDetail.setBorder(new TitledBorder("发送数据明细"));
		this.getContentPane().setLayout(frameLayout);
		GridBagConstraints gbc2 = new GridBagConstraints();
		gbc2.fill = GridBagConstraints.BOTH;
		gbc2.gridx = 0;
		gbc2.gridy = 1;
		gbc2.weightx = 1;
		gbc2.weighty = 0.87;
		this.getContentPane().add(jScrollPaneDetail, gbc2);
		// 系统设置
		this.jPanelConfig.setLayout(new GridLayout(1, 2));
		JPanel jPanelInputConfig = new JPanel();
		this.jPanelConfig.add(jPanelInputConfig);
		jPanelInputConfig.setLayout(new GridLayout(3, 1));
		JPanel jPanelUserInfo = new JPanel();
		jPanelInputConfig.add(jPanelUserInfo);
		jPanelUserInfo.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 0));
		jPanelUserInfo.add(new JLabel("用户名:"));
		jTextUser = new JTextField(15);
		jPanelUserInfo.add(jTextUser);
		jPanelUserInfo.add(new JLabel("密    码:"));
		jPasswordField = new JPasswordField(15);
		jPanelUserInfo.add(jPasswordField);

		JPanel jPanelOtherInfo = new JPanel();
		jPanelOtherInfo.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 0));
		jPanelInputConfig.add(jPanelOtherInfo);
		jPanelOtherInfo.add(new JLabel("主    题:"));
		jTextSubject = new JTextField(25);
		jPanelOtherInfo.add(jTextSubject);
		jCheckBoxIsTable = new JCheckBox("发送表格", true);
		jPanelOtherInfo.add(jCheckBoxIsTable);

		JPanel jPanelButton = new JPanel();
		jPanelButton.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 0));
		jPanelInputConfig.add(jPanelButton);

		jButtonLoad = new JButton("导入Excel");
		jPanelButton.add(jButtonLoad);
		jButtonSend = new JButton("发送邮件 ");
		jPanelButton.add(jButtonSend);

		JScrollPane jScrollPaneMailTmpl = new JScrollPane();
		jScrollPaneMailTmpl.setBorder(new TitledBorder("邮件内容"));
		jPanelConfig.add(jScrollPaneMailTmpl, 1);
		jTextPane = new JTextPane();
		jScrollPaneMailTmpl.setViewportView(jTextPane);

		// JTable
		tbsmsTableModel = new TbsmsTableModel();
		jTable = new JTable();
		jTable.setModel(tbsmsTableModel);
		jScrollPaneDetail.setViewportView(jTable);
		pack();
	}

	private void initConfig() {
		jTextUser.setText(PropParse.getInstance().getValue("vd.send.user"));
		jPasswordField.setText(PropParse.getInstance().getValue("vd.send.passwd"));
		String mailContent = PropParse.getInstance().getValue("vd.mail_content");
		try {
			mailContent = new String(mailContent.getBytes("ISO-8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		jTextPane.setText(mailContent);
		// 导入excel
		jButtonLoad.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (sendProcess.getStatus().equals(Status.SENDING)) {
					showTipMsg("邮件正在发送中，请稍后。");
					return;
				}
				FileDialog fileDialog = new FileDialog(TbsmsUI.this, "导入Excel");
				fileDialog.setMode(FileDialog.LOAD);
				fileDialog.setVisible(true);
				String file = fileDialog.getFile();
				log.info("get file:" + file);
				if (file == null || file.isEmpty()) {
					showErrMsg("未找到excel文件，请确认路径是否正确!");
					return;
				}
				file = fileDialog.getDirectory() + File.separator + file;
				XlsResource res = new XlsResource(file, Type.XLS);
				List<?> list = loadResProcess.processDetail(res);
				List<String> headers = loadResProcess.getHeader();
				tbsmsTableModel.setHeaderList(headers);
				tbsmsTableModel.setDataList(list);
				setVisible(true);
			}
		});
		// 邮件发送
		jButtonSend.addActionListener(new ActionListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void actionPerformed(ActionEvent e) {
				if(jTextUser.getText().trim().isEmpty() || jPasswordField.getText().isEmpty()){
					showTipMsg("请录入用户名和密码。");
					return;
				}
				sendProcess.setCallBack(callBack);
				sendProcess.sendMsg(jTextSubject.getText().trim(),jTextPane.getText(), tbsmsTableModel.getDataList(), 
						jTextUser.getText().trim(), jPasswordField.getText(), jCheckBoxIsTable.isSelected());
			}
		});
	}

	public void showErrMsg(String msg) {
		JOptionPane.showMessageDialog(this, "系统错误：\n" + msg);
	}

	public void showTipMsg(String msg) {
		JOptionPane.showMessageDialog(this, msg);
	}
	public void start(){
		 try {
				for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
					if ("Nimbus".equals(info.getName())) {
						UIManager.setLookAndFeel(info.getClassName());
						break;
					}
				}
			} catch (Exception ex) {
				log.error("ui start exception:", ex);
			}
			EventQueue.invokeLater(new Runnable() {
				public void run() {
					TbsmsUI.this.setVisible(true);
				}
			});
	}

	private ErrorTableCellRenderer errRender = new ErrorTableCellRenderer();
	private ProcessCallBack callBack = new ProcessCallBack() {

		@Override
		public void tipMsg(String msg) {
			showTipMsg(msg);
		}

		@Override
		public void updateStatus(int row, String status) {
			tbsmsTableModel.setValueAt(status, row, 0);
			if(status.equals(Status.FAILD.toString())){
				errRender.addRow(row);
				jTable.getColumn(jTable.getColumnName(0)).setCellRenderer(errRender);
			}
			
		}
	};

}
